package middleware

import (
    "github.com/gin-gonic/gin"
    "net/http"
    "strings"
    "time"
    "yi-shou-backstage/util"
)

// jwt中间件
func JwtToken() gin.HandlerFunc{
    return func(c *gin.Context) {
        TokenHeader := c.Request.Header.Get("Authorization")

        if TokenHeader == "" {
            c.JSON(http.StatusOK, gin.H{
                "message": "Token not Exist",
            })
            c.Abort()
            return
        }

        TokenList := strings.SplitN(TokenHeader, " ", 2)
        if len(TokenList) != 2 && TokenList[0] != "Bearer" {
            c.JSON(http.StatusOK, gin.H{
                "message": "Token format error",
            })
            c.Abort()
            return
        }

        key, err := util.CheckToken(TokenList[1])
        if err != nil {
            c.JSON(http.StatusOK, gin.H{
                "message": err,
            })
            c.Abort()
            return
        }

        if time.Now().Unix() > key.ExpiresAt {
            c.JSON(http.StatusOK, gin.H{
                "message": "Token is expired",
            })
            c.Abort()
            return
        }

        c.Set("user_id", key.UserId)
        c.Next()
    }
}
